# -*- coding: utf-8 -*-
import logging

from common.mch import handler as mch_handler
from common.withdraw import handler as withdraw_handler

from common.utils.api import check_params, get_client_ip
from common.utils import exceptions as err
from common.utils.decorator import response_wrapper

from django.views.decorators.http import require_GET, require_POST


_LOGGER = logging.getLogger(__name__)


@require_POST
@response_wrapper
def create(request):
    """
    统一提现接口
    """
    params = request.POST.dict()
    check_params(params, ['mch_id', 'out_trade_no', 'total_fee',
        'payee_no', 'payee_real_name', 'notify_url', 'sign'],
        param_type_dct={
            'mch_id': basestring,
            'out_trade_no': basestring,
    })
    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    _LOGGER.info('create_withdraw data : %s', params)
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    params['mch_create_ip'] = get_client_ip(request)
    params['sign'] = sign
    trans_info = withdraw_handler.create_withdraw(params)
    return trans_info


@require_POST
@response_wrapper
def query(request):
    """
    订单查询接口
    """
    params = request.POST.dict()
    check_params(params, ['mch_id',
        'out_trade_no', 'sign'], param_type_dct={
            'mch_id': basestring,
            'out_trade_no': basestring,
    })
    mch_id = params['mch_id']
    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    out_trade_no = params['out_trade_no']
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    order_info = withdraw_handler.get_order_by_mch(mch_id, out_trade_no)
    return {
        'order_info': order_info
    }


@require_POST
@response_wrapper
def query_channels(request):
    params = request.POST.dict()
    check_params(params, ['mch_id', 'sign'], param_type_dct={
        'mch_id': basestring,
    })
    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    channels = withdraw_handler.get_vaild_channels_by_mch(mch_id)
    return {'list': channels}
